package com.android.measuringimportanceoflectureslides.data;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Environment;
import android.text.GetChars;
import android.util.Log;
import android.widget.Toast;

public class PhotoHandler implements PictureCallback {
	
	private final Context mContext;
	 private static final String TAG = "PhotoHandler";
	
	public PhotoHandler(Context context){
		mContext = context;
	}
	
	public void onPictureTaken(byte[] pictureData, Camera camera) {
		
		File pictureFileDir = getDir();
		
		if(!pictureFileDir.exists() && !pictureFileDir.mkdirs()){
			Log.d(TAG, "Can't create directory to save image.");
			Toast.makeText(mContext, "Can't create directory to save image", 
					Toast.LENGTH_LONG).show();
			return;
		}
		
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_mm_dd_hh_mm_ss");
		String date = dateFormat.format(new Date());
		String photoFile = "Picture_" + date + ".jpg";
		
		//File.separator is a /
		String filename = pictureFileDir.getPath() + File.separator + photoFile;
		
		File pictureFile = new File(filename);
		
		FileOutputStream fos = null;
		
		try {
			fos = new FileOutputStream(pictureFile);
			fos.write(pictureData);
			Toast.makeText(mContext, "New photo saved:" + 
					photoFile, Toast.LENGTH_SHORT).show();
		}
		catch(Exception error){
			Log.d(TAG, "File " + filename + "not saved:" + error.getMessage());
			Toast.makeText(mContext, "Image could not be saved: " +  
					photoFile, Toast.LENGTH_LONG).show();
		}
		finally{
			try {
				fos.close();
			} catch (IOException e) {
				Toast.makeText(mContext, "fos could not be closed", Toast.LENGTH_SHORT).show();
				e.printStackTrace();
			}
		}
	}

	private File getDir() {
		File sdDir = Environment.
				getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
		return new File(sdDir, "CameraApiDemo");
	}

}
